"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SocketConnection = void 0;
const Config_1 = require("../../../config/Config");
const DateUtil_1 = require("../../utils/DateUtil");
const EventManager_1 = require("../../utils/EventManager");
const Logger_1 = require("../../utils/Logger");
const SocketClientMsgHandler_1 = require("./SocketClientMsgHandler");
const SocketConnectionManager_1 = require("./SocketConnectionManager");
const SocketMsg_1 = require("./SocketMsg");
const Check_Time_Inteval = 1000 * 5;
const NoMsg_Time_Inteval = 1000 * 30;
class SocketConnection {
    constructor(connection, ip) {
        this.id = 0;
        this.isDestroyed = false;
        this.gotoCloseTime = 0;
        this.connectTime = 0;
        this.timeCount = 0;
        this.lastRecvMsgTime = 0;
        this.isInternalServer = false;
        EventManager_1.EventManager.instance.on(Config_1.Config.Event_Config.Timer, this.onTimer, this);
        this.connection = connection;
        SocketConnection.id++;
        this.ip = ip;
        this.id = SocketConnection.id;
        this.connectTime = DateUtil_1.default.now();
        this.initConnect();
    }
    initConnect() {
        this.isDestroyed = false;
        this.isClosing = false;
        this.connection.on('close', () => {
            Logger_1.Logger.log('SocketConnection disconnected', this.account);
            this.destroy();
        });
        this.connection.on('message', (data) => {
            this.lastRecvMsgTime = DateUtil_1.default.now();
            this.onClientMsgHandler(data);
        });
    }
    onTimer(now) {
        if ((now - this.timeCount) >= Check_Time_Inteval) {
            this.timeCount = now;
            if (!this.isLogin()) { //连接后很久不登录释放连接 
                if (now - this.connectTime >= 1000 * 60) {
                    this.destroy();
                    return false;
                }
            }
            else {
                if (!this.isInternalServer && this.lastRecvMsgTime > 0 && (now - this.lastRecvMsgTime) >= NoMsg_Time_Inteval) {
                    this.lastRecvMsgTime = 0;
                    this.checkDestroyAccountConnect();
                }
            }
        }
        if (this.gotoCloseTime > 0 && now >= this.gotoCloseTime) {
            this.gotoCloseTime = 0;
            this.close(true);
        }
    }
    checkDestroyAccountConnect() {
        let isNeedDestroy = true;
        for (const key in Config_1.Config.ServerType_List) {
            let value = Config_1.Config.ServerType_List[key];
            if (this.account.includes(value)) {
                this.isInternalServer = true;
                isNeedDestroy = false;
                break;
            }
        }
        if (isNeedDestroy) {
            Logger_1.Logger.log("NoMsg_Time_Inteval=22=", this.account);
            this.destroy();
        }
    }
    checkConnection() {
        if (!this.connection) {
            this.destroy();
            return false;
        }
        else if (this.connection.readyState == SocketConnection.ReadyState.Close) {
            this.connection.terminate();
            this.destroy();
            return false;
        }
        return true;
    }
    gotoClose() {
        this.isClosing = true;
        this.gotoCloseTime = DateUtil_1.default.now() + 1000;
        // if(this.player){
        //     this.player.toDbStr() //数据回写
        // }
    }
    close(isForce = false) {
        if (this.connection.readyState == SocketConnection.ReadyState.Open || isForce) {
            this.connection.terminate();
            this.destroy();
        }
    }
    onClientMsgHandler(data) {
        try {
            // let byteArray: Uint8Array = new Uint8Array(data);
            // let totalPack = ProtoUtils.DeserializeBinary(ProtoConfig.basemsg, byteArray);
            // // Logger.log("onClientMsgHandler========", totalPack);
            // let req_id: number = totalPack.getReqId();
            // let proto_name: string = totalPack.getProtoName()
            // let protoData: Uint8Array = totalPack.getData();
            Logger_1.Logger.log("onClientMsgHandler===", data);
            let dataObj = JSON.parse(data);
            let msg = SocketMsg_1.SocketMsg.createSocketMsg(dataObj["id"], dataObj["data"]["protoName"], dataObj["data"]);
            if (msg.protoName.includes("req_server")) {
                SocketClientMsgHandler_1.SocketClientMsgHandler.onEventSocketGata(this, msg);
            }
            else {
            }
        }
        catch (error) {
            Logger_1.Logger.info("onClientMsgHandler======error==", error);
            Logger_1.Logger.error("onClientMsgHandler======error==", error);
        }
    }
    createSendPack(socketMsg) {
        let obj = {
            "id": socketMsg.reqId,
            "protoName": socketMsg.protoName,
            "data": socketMsg.protoData
        };
        // let serialdata: Uint8Array = socketMsg.protoData.serializeBinary();
        // let totalPack = ProtoUtils.Create(ProtoConfig.basemsg);
        // totalPack.setReqId(socketMsg.reqId)
        // totalPack.setProtoName(socketMsg.protoName)
        // totalPack.setData(serialdata);
        // return totalPack.serializeBinary();
        return JSON.stringify(obj);
    }
    createMsgToClient(reqId, protoName, respPack) {
        let socketMsg = SocketMsg_1.SocketMsg.createSocketMsg(reqId, protoName, respPack);
        // Logger.log("createMsgToClient", socketMsg)
        this.sendMsgToClient(socketMsg);
    }
    sendMsgToClient(socketMsg) {
        if (!this.checkConnection()) {
            return;
        }
        if (!this.isDestroyed) {
            // let totalPack: Uint8Array = this.createSendPack(socketMstg);
            // let sendBuff: Buffer = Buffer.from(totalPack);
            // this.connection.send(sendBuff);
            this.connection.send(this.createSendPack(socketMsg));
        }
        else {
            Logger_1.Logger.error("sendMsgToClient=error=", this, socketMsg);
        }
    }
    isLogin() {
        if (this.account && this.account != null && this.account != "") {
            return true;
        }
        else {
            return false;
        }
    }
    destroy() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.isDestroyed) {
                EventManager_1.EventManager.instance.clear(this);
                Logger_1.Logger.log("socketconnection destroy=", this.account);
                this.isDestroyed = true;
                this.connection = null;
                this.account = null;
                // if (this.user) {
                //     this.user.destroy()
                // }
                // this.user = null
                SocketConnectionManager_1.SocketConnectionManager.instance.removeSocketConnection(this);
            }
        });
    }
}
exports.SocketConnection = SocketConnection;
SocketConnection.ReadyState = {
    Open: 1,
    Close: 3
};
SocketConnection.id = 0;
